<template>
  <div>
    <div
      style="
        margin-top: 40px;
        margin-left: 20px;
        margin-right: 20px;
        width: auto;
        padding: 10px;
        background-color: #fff;
        height: auto;
        /* border: 1px solid red; */
        box-shadow: red;
      "
    >
      <!-- <h1 >IP流量</h1> -->
      <div
        style="
          width: 100%;
          height: 30px;
          float: left;
          margin-left: 30px;
          margin-bottom: 30px;
        "
      >
        <p style="size: 18px">IP流量</p>
      </div>
      <div
        style="
          width: auto;
          height: 450px;
          border: 1px solid #cecece;
          border-radius: 10px;
          margin-left: 20px;
          margin-right: 20px;
        "
      >
        <div
          style="
            margin-left: 5px;
            width: 580px;
            height: 400px;
            float: left;
            /* background-color: blue; */
          "
        >
          <div style="float: left">
            <el-form
              :inline="true"
              :model="formInline"
              class="demo-form-inline"
              style="margin-left: 20px; margin-top: 20px"
            >
              <el-form-item label="资产详情">
                <el-input
                  v-model="formInline.user"
                  placeholder="监控IP"
                ></el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
              </el-form-item>
            </el-form>
          </div>

          <div style="float: left">
            <el-table
              :data="tableData"
              stripe
              style="width: 100%"
              :header-cell-style="{ background: '#eff3f8' }"
            >
              <el-table-column prop="order" label="排序" width="100">
              </el-table-column>
              <el-table-column prop="address" label="IP地址" width="150">
              </el-table-column>
              <el-table-column prop="kind" label="IP类型" width="100">
              </el-table-column>
              <el-table-column prop="netsum" label="总流量峰值" width="100">
              </el-table-column>
              <el-table-column prop="operate" label="操作" width="100">
              </el-table-column>
            </el-table>
          </div>
        </div>

        <div
          style="
            width: 570px;
            margin-left: 10px;
            height: 400px;
            float: left;
            /* background-color: blueviolet; */
          "
        >
          <div style="width: 570px; height: 30px; margin-bottom: 10px">
            <span style="float: left; color: #606266">响应峰值：232Mpbs</span>
            <span style="float: right; color: #606266">查看日志 </span>
          </div>
          <div id="traffic-chart" style="width: 570px; height: 360px"></div>
        </div>
      </div>
    </div>
    <div
      style="
        width: auto;
        height: 500px;
   
        margin-left: 50px;
        margin-right: 45px;
        margin-top: 20px;
        border: 1px solid #cecece;
        border-radius: 10px;
      "
    >
      <div
        style="
          width: 100%;
          margin-left: 10px;
          height: 30px;
          float: left;
          margin-bottom: 30px;
        "
      >
        <p style="size: 18px">流量访问Top</p>
      </div>
      <div
        style="
          width: 560px;
          height: 370px;
          float: left;
          margin-left: 30px;
        "
      >
        <div ref="chart" style="height: 400px"></div>
      </div>
      <div
        style="
          width: 560px;
          height: 370px;
          float: left;
          margin-left: 10px;
        "
      >
        <div ref="piechart" style="height: 400px"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import axios from "axios";
import { getaddr } from "@/api/rate/rate";
export default {
  data() {
    return {
      select: "",
      trafficDataList: [], // 存储接收到的流量数据列表
      socket: null, // WebSocket 实例
      formInline: {
        user: "",
        region: "",
      },
      formInlineOptions: [
        {
          value: "选项1",
          label: "黄金糕",
        },
        {
          value: "选项2",
          label: "双皮奶",
        },
        {
          value: "选项3",
          label: "蚵仔煎",
        },
      ],

      tableData: [
        {
          order: "1",
          address: "47.108.142.219",
          kind: "ECS公网IP",
          netsum: "7.66Mbps",
          operate: "查看详情",
        },



      ],
    };
  },

  mounted() {
    // 创建 WebSocket 连接
    this.socket = new WebSocket("ws://localhost:8080/ws/traffic");

    // 连接成功后
    this.socket.onopen = () => {
      console.log("WebSocket 连接成功！");
    };

    // 接收消息并更新流量数据
    this.socket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      this.trafficDataList = data;
      this.updateChart(data); // 更新ECharts图表
    };

    // 处理 WebSocket 错误
    this.socket.onerror = (error) => {
      console.error("WebSocket 错误: ", error);
    };

    // 连接关闭时
    this.socket.onclose = () => {
      console.log("WebSocket 连接关闭！");
    };

    this.fetchTrafficStats("2025-02-28 00:00:00", "2025-03-01 23:59:59").then(
      (statsData) => {
        console.log("statsData:", statsData);
        this.renderChart(statsData);
      }
    );
  },
  beforeDestroy() {
    // 在组件销毁时关闭 WebSocket 连接
    if (this.socket) {
      this.socket.close();
    }
  },
  methods: {
    // 更新图表
    updateChart(data) {
      const chart = echarts.init(document.getElementById("traffic-chart"));
      const timestamps = data.map((item) => item.timestamp);
      const totalBytes = data.map((item) => item.total_bytes / 1024 / 1024); // 转换为Mbps
      const totalPackets = data.map((item) => item.total_packets);

      // 计算横坐标标签的间隔，确保只显示五个标签
      const interval = Math.ceil(timestamps.length / 5);

      const option = {
        title: {
          text: "实时响应峰值",
          subtext: "数据单位：Mbps", // 显示单位
          left: "center",
        },
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            let result = `${params[0].axisValueLabel}<br/>`;
            params.forEach(function (item) {
              result += `${item.marker}${item.seriesName}：${item.value} Mbps<br/>`;
            });
            return result;
          },
        },
        xAxis: {
          type: "category",
          data: timestamps,
          axisLabel: {
            interval: interval, // 设置标签显示间隔
            rotate: 0, // 不旋转标签
            formatter: function (value) {
              // 只显示月/日 时：分，不显示年份
              const date = new Date(value);
              return `${date.getMonth() + 1}/${date.getDate()} ${date
                .getHours()
                .toString()
                .padStart(2, "0")}:${date
                .getMinutes()
                .toString()
                .padStart(2, "0")}`;
            },
          },
        },
        yAxis: {
          type: "value",
          name: "流量 (Mbps)",
          axisLabel: {
            formatter: "{value} Mbps",
          },
        },
        series: [
          {
            name: "流量字节",
            type: "line",
            data: totalBytes,
            smooth: true, // 平滑曲线
            lineStyle: {
              color: "#3e8f7d",
            },
            areaStyle: {
              color: "rgba(62, 143, 125, 0.2)",
            },
          },
          {
            name: "数据包数",
            type: "line",
            data: totalPackets,
            smooth: true,
            lineStyle: {
              color: "#f39c12",
            },
            areaStyle: {
              color: "rgba(243, 156, 18, 0.2)",
            },
          },
        ],
      };

      chart.setOption(option);
    },

    // 获取流量地理统计数据
    async fetchTrafficStats(startTime, endTime) {
      try {
        // 使用 getaddr 函数发起请求
        const response = await getaddr({
          startTime,
          endTime,
        });

        console.log("newresponse:", response);

        console.log("response:", response);
        return response;
      } catch (error) {
        console.error("获取数据失败", error);
      }
    },

    // 渲染地理统计图表
    renderChart(data) {
      console.log("data:", data);

      const chart = echarts.init(this.$refs.chart);

      // 提取数据
      const countriesCities = data.map((item) => {
        // 国家和城市都是 'Unknown'，则替换为 '本地'
        const country = item.country === "Unknown" ? "本地" : item.country;
        const city = item.city === "Unknown" ? "本地" : item.city;

        return `${country} - ${city}`;
      });

      const totalPackets = data.map((item) => item.totalPackets); // 总数据包数

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
        },
        xAxis: {
          type: "value", // 横向条形图，x轴为数值轴
          name: "流量", // 设置x轴名称
        },
        yAxis: {
          type: "category", // y轴为分类轴
          data: countriesCities, // x轴的类别
        },
        series: [
          {
            name: "流量",
            type: "bar", // 条形图
            data: totalPackets,
            itemStyle: {
              color: "#0088ff", // 设置条形图颜色
            },
          },
        ],
      };

      chart.setOption(option);

      // 渲染饼图
      const pieChart = echarts.init(this.$refs.piechart); // 获取饼图容器

      // 处理饼图数据：根据 IP 地址计算每个 IP 的流量或数据包数
      const ipStats = {};
      data.forEach((item) => {
        if (item.ip && item.totalPackets) {
          if (!ipStats[item.ip]) {
            ipStats[item.ip] = 0;
          }
          ipStats[item.ip] += item.totalPackets; // 累加每个 IP 的流量
        }
      });

      const pieData = Object.keys(ipStats).map((ip) => ({
        name: ip,
        value: ipStats[ip],
      }));

      // 饼图配置
      const pieOption = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          left: "left",
          data: pieData.map((item) => item.name),
        },
        series: [
          {
            name: "IP流量占比",
            type: "pie",
            radius: "55%",
            center: ["50%", "60%"],
            data: pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };

      pieChart.setOption(pieOption);
    },


  },
};
</script>

<style scoped>
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

th,
td {
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}

#traffic-chart {
  width: 100%;
  height: 400px;
}
</style>
